# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.


from web_lib.page import Page
from web_lib.webutils import Response, expose , json
from dao.Role import Role
from lib.utils import prep2json

@expose('/pg/as_Ruolo/<action>')
@expose('/pg/as_Ruolo/')
@expose('/pg/as_Ruolo')
def anagraficaRuolo(req, action=None):
    """
    """
    def __show__(req, action=None):
        pageData = {'file' : "/pg/as_Ruolo"}
        return Page(req).render(pageData)

    def __list__(req, action=None):
        sorting = req.args.get("jtSorting")
        offset = req.args.get("jtStartIndex")
        batchSize = req.args.get("jtPageSize")
        fk_nome =  req.form.get("fk_name")
        daos = Role().select(name=fk_nome,
                                        batchSize=batchSize,
                                        offset=offset,
                                        orderBy=sorting)
        count = Role().count(name=fk_nome,
                                        batchSize=None)
        item = {
            "Result":"OK",
            "TotalRecordCount": count,
            "Records": prep2json(daos)}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __create__update__(req, action=None):
        """"""
        id = req.form.get("id")
        if id:
            d = Role().getRecord(id=int(id))
        else:
            d = Role()
        d.name = str(req.form.get("name"))
        d.descrizione = str(req.form.get("descrizione"))
        d.active = True
        #TODO: FORZO QUESTO VALORE ANDRA MAGARI IN SEGUITO GESTITO
        try:
            d.persist()
            if id:
                item = {"Result":"OK"}
            else:
                item = {"Result":"OK","Record":d.jsanity()}
        except:
            item = {
                "Result":"ERROR",
                "Message": "Creazione o modifica nuova riga non riuscita"}

        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    def __delete__(req, action=None):
        """Cancella una riga"""
        id = int(req.form.get("id"))
        d = Role().getRecord(id=id)
        try:
            d.delete()
            item = {"Result": "OK", }
        except:
            item = {
                "Result":"ERROR",
                "Message": "Cancellazione riga non riuscita"}
        jasoned = json.dumps(item, ensure_ascii=False, encoding='utf8')
        return Response(jasoned)

    if action=="List":
        return __list__ (req, action=action)
    elif action=="show":
        return __show__(req, action=action)
    elif action=="Create" or action == "Update":
        return __create__update__(req, action=action)
    elif action=="Delete":
        return __delete__(req, action=action)
    else:
        return __show__(req, action=action)
